package com.titaniume.java4;

import org.junit.Test;

import java.util.Optional;

/**
 *@program: JavaSenior
 *@description: Optional 为了避免出现空指针
 *
 *  OfNullable
 *  orElse
 *
 *@author: renfei.huang
 *@create: 2021-11-03 09:37
 */
public class OptionalTest {


//     Optional.of(T t) : 创建一个 Optional 实例，t必须非空；
//      Optional.empty() : 创建一个空的 Optional 实例
// Optional.ofNullable(T t)：t可以为nu
    @Test
    public  void test1(){

        Girl girl = new Girl();
        //of() 必须保证t非空
        Optional<Girl> optionalGirl = Optional.of(girl);
    }

    @Test
    public  void test2(){
        Girl girl = new Girl();
//        girl = null;
        //Optional.empty(T t) : t可以为空
        Optional<Girl> optionalGirl = Optional.ofNullable(girl);
        System.out.println(optionalGirl);
        Girl girl1 = optionalGirl.orElse(new Girl("杨幂"));
        System.out.println(girl1);

    }


    public String getGirlName(Boy boy){

        //出现空指针
        return  boy.getGirl().getName();
    }

    @Test
    public  void test3(){
       Boy boy = new Boy();
       boy = null;
        String girlName = getGirlName(boy);
        System.out.println(girlName);
    }


    //优化后getGirlName1()
    public String getGirlName1(Boy boy){
        if(boy != null){
            Girl girl = boy.getGirl();
            if (girl != null) {
                return  girl.getName();
            }

        }
        return  null;
    }

    @Test
    public  void test4(){
        Boy boy = new Boy();
        boy = null;
        String girlName = getGirlName1(boy);
        System.out.println(girlName);
    }


    //使用Optional类的getGirlName2()
    public String getGirlName2(Boy boy){

        Optional<Boy> boyOptional = Optional.ofNullable(boy);
        // T orElse(T other) ：如果有值则将其返回，否则返回指定的other对象。

        //此时的boy1一定非空
        Boy boy1 = boyOptional.orElse(new Boy(new Girl("苍老师")));

        Girl girl = boy1.getGirl();

        Optional<Girl> girlOptional = Optional.ofNullable(girl);

        //此时的girl1一定非空
        Girl girl1 = girlOptional.orElse(new Girl("玛丽莲.梦露"));
        System.out.println(girl1.getName());

        return null;
    }


    @Test
    public  void test5(){
        Boy boy = new Boy();
        boy = null;
        boy = new Boy(new Girl("xx老师"));
        String girlName2 = getGirlName2(boy);
        System.out.println();
    }

}
